//监听15001端口，管理设备上下线
//xx+22为数据为设备下线，sx + 22 位数据位上线
//用户首次连接须发送22位数据的注册包

const net = require('net')

const server = net.createServer().listen(15001);
let webClientPoll = {}
let ipport = {}
server.on("connection", (c) => {
    c.on('data', (data) => {
        let dataStr = data.toString();
        //如果数据长度为22，则为注册包,储存设备
        console.log(dataStr);
        if (dataStr.length == 22) {
            //绑定连接，设备号和ip port
            webClientPoll[dataStr] = c;
            ipport[c.remoteAddress + c.remotePort] = dataStr;
        } else if (webClientPoll[dataStr.substr(2)]) {
            if (dataStr.substr(0, 2) === 'xx') {
                webClientPoll[dataStr.substr(2)].write(dataStr.substr(2) + ',outline')
            }
            if (dataStr.substr(0, 2) === 'sx') {
                webClientPoll[dataStr.substr(2)].write(dataStr.substr(2) + ',online')

            }
        }

    })
    c.on('close', () => {
        delete webClientPoll[ipport[c.remoteAddress + c.remotePort]];
        delete ipport[c.remoteAddress + c.remotePort];

    })

    c.on('error', (err) => {
        // console.warn(err);
        delete webClientPoll[ipport[c.remoteAddress + c.remotePort]];
        delete ipport[c.remoteAddress + c.remotePort];
        c.destroy()

    })
})